<?php

namespace App\Http\Controllers;

use App\Models\Attribute;
use App\Models\AttributeValue;
use App\Models\ProductStock;
use App\Models\Upload as UploadModel;
use Illuminate\Http\Request;
use App\Models\Product;
use App\Models\Category;
use App\Models\SubCategory;
use App\Models\SubSubCategory;
use App\Models\Brand;
use App\Models\User;
use Auth;
use App\Models\ProductsImport;
use App\Models\ProductsExport;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Image;
use PDF;
use Excel;
use Illuminate\Support\Str;

class ProductBulkUploadController extends Controller
{
    public function index()
    {
        $categories = Category::where('parent_id', 0)
            ->where('digital', 0)
            ->with('childrenCategories')
            ->get();
        if (Auth::user()->user_type == 'seller') {
            if (Auth::user()->seller->verification_status) {
                return view('frontend.user.seller.product_bulk_upload.index', compact('categories'));
            } else {
                flash('Your shop is not verified yet!')->warning();
                return back();
            }
        } elseif (Auth::user()->user_type == 'admin' || Auth::user()->user_type == 'staff') {
            return view('backend.product.bulk_upload.index', compact('categories'));
        }
    }

    public function export()
    {
        return Excel::download(new ProductsExport, 'products.xlsx');
    }

    public function pdf_download_category()
    {
        $categories = Category::all();

        return PDF::loadView('backend.downloads.category', [
            'categories' => $categories,
        ], [], [])->download('category.pdf');
    }

    public function pdf_download_brand()
    {
        $brands = Brand::all();

        return PDF::loadView('backend.downloads.brand', [
            'brands' => $brands,
        ], [], [])->download('brands.pdf');
    }

    public function pdf_download_seller()
    {
        $users = User::where('user_type', 'seller')->get();

        return PDF::loadView('backend.downloads.user', [
            'users' => $users,
        ], [], [])->download('user.pdf');

    }

    public function bulk_upload(Request $request)
    {
        set_time_limit(600);
        ini_set('memory_limit', '512M');
        if ($request->hasFile('bulk_file')) {
            set_time_limit(0);
            $category_id = $request->post('category_id', 0);
            $file = $request->file('bulk_file');
            $file_path = Storage::disk('local')->putFile('excel', $file);
            $file_path = public_path($file_path);

            $column = [
                [1 => '图片链接'],
                [2 => '图片链接1'],
                [3 => '图片链接2'],
                [4 => '图片链接3'],
                [5 => '图片链接4'],
                [6 => '页面网址'],
                [7 => '字段'],
                [8 => '介绍'],
                [9 => '商品标题'],
                [10 => '产品类1'],
                [11 => '产品类2'],
                [12 => '价格'],
                [13 => '品牌'],
            ];
            $data = import_excel($file_path, $column);
            $filter_data = [];
            for ($index = 0; $index < count($data); $index++) {
                $data[$index]['价格'] = str_replace('$', '', $data[$index]['价格']);
                $filter_data[] = $data[$index];
            }
            $result = collect($filter_data);
            $product_list = $result->groupBy('页面网址')->all();
//            dd($product_list);

            $attribute_group_color = Attribute::where('name', 'Color')->first();
            $attribute_group_size = Attribute::where('name', 'Size')->first();
            foreach ($product_list as $product_url => $item) {
                try {
//                    DB::beginTransaction();
                    // 第一遍处理基础数据
                    $attr_arr = $temp_choice = [];
                    $choice_color_arr = ['attribute_id' => $attribute_group_color->id, 'values' => []];
                    $choice_size_arr = ['attribute_id' => $attribute_group_size->id, 'values' => []];
                    $description = '';
                    $product_name = '';
                    $brand_name = '';
                    $min_price = $max_price = 0;
                    foreach ($item as $idx => $v) {
                        if(!$v['图片链接'] || !$v['价格'] || !$v['商品标题']) {
                            continue;
                        }
                        // 处理图片新增
                        $tag_list = ['图片链接', '图片链接1', '图片链接2', '图片链接3', '图片链接4'];
                        $image_ids = [];
                        foreach ($tag_list as $k => $tag) {
                            if (!trim($v[$tag])) {
                                continue;
                            }
                            $image_model = UploadModel::updateOrCreate([
                                'file_original_name' => $v[$tag]
                            ], [
                                'file_name' => $v[$tag],
                                'user_id' => 0,
                                'file_size' => 8888,
                                'extension' => 'jpg',
                                'type' => 'image'
                            ]);
                            $image_ids[] = $image_model->id;
                        }
//                    dd($attr_arr);
                        // 处理属性产品类1和产品类2
                        if (trim($v['产品类1'])) {
                            $attribute_value_color_model = AttributeValue::updateOrCreate([
                                'attribute_id' => $attribute_group_color->id, 'value' => $v['产品类1']
                            ]);
                            $attr_arr[] = $attribute_group_color->id;
                            $attr_arr = array_unique($attr_arr);
                            $choice_color_arr['values'][] = $v['产品类1'];
                            $choice_color_arr['values'] = array_unique($choice_color_arr['values']);
                        }
                        if (trim($v['产品类2'])) {
                            $attribute_value_size_model = AttributeValue::updateOrCreate([
                                'attribute_id' => $attribute_group_size->id, 'value' => $v['产品类2']
                            ]);
                            $attr_arr[] = $attribute_group_size->id;
                            $attr_arr = array_unique($attr_arr);
                            $choice_size_arr['values'][] = $v['产品类2'];
                            $choice_size_arr['values'] = array_unique($choice_size_arr['values']);
                        }

                        $description = $v['介绍'];
                        $product_name = $v['商品标题'];
                        $brand_name = $v['品牌'];
                        $min_price = $min_price > 0 ? min($min_price, $v['价格']) : $v['价格'];
                        $max_price = $max_price > 0 ? max($max_price, $v['价格']) : $v['价格'];
                    }

                    if(in_array($attribute_group_color->id, $attr_arr)) {
                        $temp_choice[] = $choice_color_arr;
                    }
                    if(in_array($attribute_group_size->id, $attr_arr)) {
                        $temp_choice[] = $choice_size_arr;
                    }

                    if(!$product_name || !$min_price || count($image_ids) == 0) {
                        continue;
                    }
                    $brand_model = Brand::updateOrCreate([
                        'name' => $brand_name,
                    ], [
                        'logo' => 0,
                        'top' => 0,
                        'slug' => $brand_name,
                        'meta_title' => $brand_name,
                        'meta_description' => $brand_name,
                    ]);
                    // 主档案商品
                    $product_model = Product::create([
                        'name' => $product_name,
                        'user_id' => 1,
                        'category_id' => $category_id,
                        'brand_id' => $brand_model->id,
                        'photos' => implode($image_ids, ','),
                        'thumbnail_img' => $image_ids ? $image_ids[0] : '',
                        'description' => $description,
                        'unit_price' => $min_price,
                        'purchase_price' => 0,
                        'variant_product' => count($item) > 1 ? 1 : 0,
                        'attributes' => json_encode($attr_arr),
                        'choice_options' => json_encode($temp_choice),
                        'colors' => json_encode([]),
                        'published' => 1,
                        'approved' => 1,
                        'current_stock' => count($item) * 1000,
                        'min_qty' => 1,
                        'low_stock_quantity' => 1,
                        'discount' => 0,
                        'discount_type' => 'amount',
                        'shipping_type' => 'free',
                        'shipping_cost' => 0,
                        'meta_title' => $product_name,
                        'slug' => $product_name,
                        'refundable' => 0,
                        'cpk' => 1
                    ]);

                    // 第二轮处理子规格插入
                    foreach ($item as $idx => $v) {
                        if(!$v['图片链接'] || !$v['价格'] || !$v['商品标题']) {
                            continue;
                        }
                        $sku_arr = [];
                        if (trim($v['产品类1'])) {
                            $sku_arr[] = str_replace(' ', '', $v['产品类1']);
                        }
                        if (trim($v['产品类2'])) {
                            $sku_arr[] = str_replace(' ', '', $v['产品类2']);
                        }
                        ProductStock::create([
                            'product_id' => $product_model->id,
                            'variant' => implode('-', $sku_arr),
                            'sku' => implode('-', $sku_arr),
                            'price' => $v['价格'] * 0.75,
                            'qty' => 1000
                        ]);
                    }
//                    DB::commit();
                } catch (\Exception $e) {
//                    DB::rollBack();
                    dd($e);
                }

            }
        }

        return back();
    }

}
